package com.tanhua.dubbo.api.mongo;

import com.tanhua.domain.mongo.VoiceRemainTime;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

@Service
public class VoiceRemainTimeApiImpl implements VoiceRemainTimeApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 根据用户id查询数据
     * @param userId
     * @return VoiceRemainTime
     */
    @Override
    public VoiceRemainTime findVoice(Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        return mongoTemplate.findOne(query, VoiceRemainTime.class);
    }

    /**
     * 保存今日接收语音剩余次数
     * @param voiceRemainTime
     */
    @Override
    public void save(VoiceRemainTime voiceRemainTime) {
        mongoTemplate.save(voiceRemainTime);
    }

    /**
     * 更新今日接收语音剩余次数
     * @param voiceRemainTime
     */
    @Override
    public void update(VoiceRemainTime voiceRemainTime) {
        ObjectId objectId = voiceRemainTime.getId();
        Query query = new Query(Criteria.where("_id").is(objectId));
        Update update = new Update();
        update.set("remainingTimes", voiceRemainTime.getRemainingTimes());
        mongoTemplate.updateFirst(query,update,VoiceRemainTime.class);
    }

    /**
     * 更新今日剩余接收语音次数
     * @param remainingTimes
     */
    @Override
    public void updateStatus(Integer remainingTimes) {
        Query query = new Query();
        Update update = new Update();
        update.set("remainingTimes", remainingTimes);
        mongoTemplate.updateMulti(query,update,VoiceRemainTime.class);
    }
}
